package com.buka.service.impl;

import com.buka.domain.ResponseResult;
import com.buka.pojo.LoginUser;
import com.buka.pojo.User;
import com.buka.service.BlogLoginService;
import com.buka.util.BeanCopyUtils;
import com.buka.util.JwtUtil;
import com.buka.util.RedisUtil;
import com.buka.vo.UserInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class BlogLoginServiceImpl implements BlogLoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword(), null);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        long userId = loginUser.getUser().getId();
        String token = JwtUtil.getToken(String.valueOf(userId));
        redisUtil.set("bloglogin:" + userId, loginUser);

        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("userInfo", userInfoVo);
        return ResponseResult.okResult(map);
    }

    @Override
    public ResponseResult logout() {
        //获取token 解析获取userid
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //获取userid
        Long userId = loginUser.getUser().getId();
        //删除redis中的用户信息
        redisUtil.remove("bloglogin:" + userId);
        return ResponseResult.okResult();

    }
}
